//
//  SNEquipmentViewController.m
//  project
//
//  Created by 黄建华 on 2017/11/20.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNEquipmentViewController.h"
#import "BlueToothViewController.h"
#import "CameraViewController.h"
#import "FindBlueViewController.h"
#import "DeviceSetViewController.h"
#import "HealthSetViewController.h"
#import "ScheduleViewController.h"
#import "AlarmViewController.h"
#import "MessagePushViewController.h"
#import "FindBandView.h"
@interface SNEquipmentViewController ()
@property(nonatomic, strong) UILabel      *titleLabel;
@property(nonatomic, strong) UILabel      *powerLabel;
@property(nonatomic, strong) UILabel      *macLabel;
@property (nonatomic, strong) UIImageView *animateView;
@property (nonatomic, strong) UIView      *bgView;
@end

@implementation SNEquipmentViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addHeadeView];
    [self addBottomView];
}

- (void)addHeadeView {
    UIImage     *backImage     = UIImageNamed(@"背景");
    UIImageView *backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), HHHWIDTH, HHHWIDTH*backImage.size.height/backImage.size.width)];
    
    backImageView.userInteractionEnabled = YES;
    backImageView.image                  = backImage;
    [self.view addSubview:backImageView];
    
    _titleLabel               = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), HHHWIDTH, 44)];
    _titleLabel.text          = @"";
    _titleLabel.font          = SNFONT(18.);
    _titleLabel.textColor     = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_titleLabel];
    
    UIButton *setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    setBtn.frame = CGRectMake(HHHWIDTH-44-10, 20+FitSimpleIpx(0, 20)+5, 44, 44);
    [setBtn setImage:[UIImage imageWithImageName:@"设置1"] forState:UIControlStateNormal];
    [setBtn setTintColor:[UIColor whiteColor]];
    [setBtn addTouchUpTarget:self action:@selector(pushToSetVC:)];
    [self.view addSubview:setBtn];
    
    _powerLabel               = [[UILabel alloc]initWithFrame:CGRectMake(FitW(20), backImageView.height*0.332, HHHWIDTH-FitW(20), FitH(25))];
    _powerLabel.textAlignment = NSTextAlignmentLeft;
    _powerLabel.font          = SNFONTMIN(15);
    _powerLabel.textColor     = [UIColor whiteColor];
    [self.view addSubview:_powerLabel];
    
    _macLabel               = [[UILabel alloc]initWithFrame:CGRectMake(FitW(20), _powerLabel.origin.y +35, HHHWIDTH-FitW(20), FitH(20))];
    _macLabel.textAlignment = NSTextAlignmentLeft;
    _macLabel.font          = SNFONTMIN(15);
    _macLabel.textColor     = [UIColor whiteColor];
    [self.view addSubview:_macLabel];
}

- (void)addBottomView {
    NSArray *imageArr = @[@"相机(1)", @"搜索", @"健康", @"日程(1)", @"闹钟(1)", @"推送"];
    NSArray *titleArr = @[HHH_Text(@"远程相机"), HHH_Text(@"查找手环"), HHH_Text(@"健康提醒"), HHH_Text(@"日程管理"), HHH_Text(@"闹钟"), HHH_Text(@"推送")];
    CGFloat width     = (HHHWIDTH-FitW(20))/3;
    CGFloat y         = (HHHHEIGHT-width-FitH(20))/2;
    
    for (int i = 0; i < 6; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(FitW(10)+width*(i%3), y+(width+FitH(20))*(i/3), width, width+FitH(20));
        btn.tag   = 100+i;
        [btn setImageNormal:imageArr[i]];
        [btn addTouchUpTarget:self action:@selector(btnClick:)];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, width-FitH(20), width, FitH(20))];
        label.text          = titleArr[i];
        label.font          = [UIFont systemFontOfSize:FitFont(14)];
        label.textColor     = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        [btn addSubview:label];
        
        [self.view addSubview:btn];
    }
}

- (void)btnClick:(UIButton *)sender {
    sender.enabled = NO;
    if (sender.tag == 100) {
        CameraViewController *cameraVC = [[CameraViewController alloc]init];
        CustomTabBar         *tabBar   = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [self.navigationController pushViewController:cameraVC animated:YES];
    } else if (sender.tag == 101) {
        FindBandView *findBandView = [[FindBandView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, HHHHEIGHT)];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:findBandView];
        [findBandView animationUp];
        [KK_BLESend sendSetFindBle:YES withUpdateBlock:^(id object, KKBLEAcceptType type)
         {
         }];
    } else if (sender.tag == 102) {
        HealthSetViewController *healthVC = [[HealthSetViewController alloc]init];
        CustomTabBar            *tabBar   = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [self.navigationController pushViewController:healthVC animated:YES];
    } else if (sender.tag == 103) {
        ScheduleViewController *scheduleVC = [[ScheduleViewController alloc]init];
        CustomTabBar           *tabBar     = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [self.navigationController pushViewController:scheduleVC animated:YES];
    } else if (sender.tag == 104) {
        AlarmViewController *alarmVC = [[AlarmViewController alloc]init];
        CustomTabBar        *tabBar  = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [self.navigationController pushViewController:alarmVC animated:YES];
    } else if (sender.tag == 105) {
        MessagePushViewController *pushVC = [[MessagePushViewController alloc]init];
        CustomTabBar              *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [self.navigationController pushViewController:pushVC animated:YES];
    }
    sender.enabled = YES;
}

- (void)pushToSetVC:(UIButton *)sender {
    sender.enabled = NO;
    DeviceSetViewController *deviceVC = [[DeviceSetViewController alloc]init];
    CustomTabBar            *tabBar   = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
    [self.navigationController pushViewController:deviceVC animated:YES];
    sender.enabled = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSInteger width = 0;
    if (KK_ShareData.lastVcTag > KK_ShareData.currentVCTag) {
        width = HHHWIDTH;
    }
    if (KK_ShareData.lastVcTag < KK_ShareData.currentVCTag) {
        width = -HHHWIDTH;
    }
    
    if (KK_ShareData.lastVcTag == KK_ShareData.currentVCTag) {
        width = 0;
    }
    if (width != 0) {
        if (_bgView) {
            [_bgView removeFromSuperview];
            _bgView = nil;
        }
        if (_animateView) {
            [_animateView removeFromSuperview];
            _animateView = nil;
        }
        
        _animateView = [[UIImageView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_animateView];
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(HHHWIDTH, HHHHEIGHT), NO, 0.0);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        _animateView.image = viewImage;
        
        _bgView                 = [[UIView alloc] initWithFrame:self.view.frame];
        _bgView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_bgView];
        [self.view bringSubviewToFront:_animateView];
        _animateView.frame  = SNFRAME(width, 0, HHHWIDTH, HHHHEIGHT);
        _animateView.hidden = NO;
        _bgView.hidden      = NO;
        DEF_WEAKSELF_(SNEquipmentViewController)
        [UIView animateWithDuration: VIEWANIMATETIME animations:^{
            _animateView.frame = SNFRAME(0, 0, HHHWIDTH, HHHHEIGHT);
        } completion:^(BOOL finished) {
            _animateView.hidden = YES;
            _bgView.hidden = YES;
            [weakSelf loadBleView];
        }];
    }
}

- (void)loadBleView {
    if (!KK_BLEConnect.model.isConnected) { // 手环绑定界面
        FindBlueViewController *findVC = [[FindBlueViewController alloc]init];
        [self.navigationController pushViewController:findVC animated:NO];
    } else { // 设备界面
        _titleLabel.text = [NSString stringWithFormat:@"%@ %@", SN_Text(@"已连接"), KK_BLEModel.bleName ? KK_BLEModel.bleName : @""];
        _powerLabel.text = [NSString stringWithFormat:@"%@: %ld%@", SN_Text(@"当前电量"), (long)SN_USER.bleBatteryQuantity, @"%"];
        _macLabel.text   = [NSString stringWithFormat:@"MAC: %@", KK_BLEModel.bleMAC.uppercaseString ? KK_BLEModel.bleMAC.uppercaseString : @""];
        [SN_Net getAppUpdateInfoFromServerWithSuccess:^(id object) {
        } fail:^(id object) {
        }];
        if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
            for (UIButton *btn in self.view.subviews) {
                if (btn.tag == 103) {
                    UIButton *badge = [UIButton buttonWithType:UIButtonTypeCustom];
                    badge.frame              = CGRectMake(btn.width*0.7, btn.height *0.25, 20, 20);
                    badge.layer.cornerRadius = 10;
                    badge.clipsToBounds      = YES;
                    badge.backgroundColor    = [UIColor redColor];
                    badge.titleNormal        = [NSString stringWithFormat:@"%ld", [UIApplication sharedApplication].applicationIconBadgeNumber];
                    badge.titleColorNormal   = [UIColor whiteColor];
                    [btn addSubview:badge];
                }
            }
        } else {
            for (UIButton *btn in self.view.subviews) {
                if (btn.tag == 103) {
                    for (UIControl *view in btn.subviews) {
                        if ([view isKindOfClass:[UIButton class]]) {
                            [view removeFromSuperview];
                        }
                    }
                }
            }
        }
    }
}

- (void)updateModel:(KKBLEModel *)model type:(KKBLEUpdateType)type {
    if (!KK_BLEConnect.model.isConnected) { // 手环绑定界面
        FindBlueViewController *findVC = [[FindBlueViewController alloc]init];
        [self.navigationController pushViewController:findVC animated:NO];
    }
}

// 通知界面接收数据刷新相应界面的UI UpdateUiType
- (void)updateView:(KKBLEAcceptType)type {
    if (type == KKBLEAcceptTypeDevideInfo) {
        NSLog(@"设备界面更新设备信息>>>>>");
        _powerLabel.text = [NSString stringWithFormat:@"%@: %ld%@", SN_Text(@"当前电量"), (long)KK_BLEModel.batteryQuantity, @"%"];
    }
    if (type == KKBLEAcceptTypeDevideMAC) {
        _macLabel.text = [NSString stringWithFormat:@"MAC: %@", KK_BLEModel.bleMAC.uppercaseString];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

